<template>
  <lay-layer
    v-model="visible"
    :title="mode === 'add' ? '新增品牌' : '编辑品牌'"
    :area="['600px', '700px']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="brand-dialog">
      <lay-form ref="formRef" :model="formData" required>
        <lay-form-item label="品牌名称" prop="name" required>
          <lay-input 
            v-model="formData.name" 
            placeholder="请输入品牌中文名称"
            :maxlength="100"
          />
        </lay-form-item>



        <lay-form-item label="品牌Logo" prop="logo">
          <div class="logo-upload">
            <div v-if="formData.logo" class="logo-preview">
              <img :src="formData.logo" alt="品牌Logo" />
              <div class="logo-actions">
                <lay-button size="xs" @click="handleLogoChange">更换</lay-button>
                <lay-button size="xs" type="danger" @click="handleLogoRemove">删除</lay-button>
              </div>
            </div>
            <div v-else class="logo-upload-area" @click="handleLogoUpload">
              <lay-icon type="layui-icon-add-1" size="24"></lay-icon>
              <div>点击上传Logo</div>
              <div class="upload-tip">支持 JPG、PNG 格式，建议尺寸 200x200px</div>
            </div>
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              style="display: none" 
              @change="handleFileChange"
            />
          </div>
        </lay-form-item>

        <lay-form-item label="品牌描述" prop="description">
          <lay-textarea 
            v-model="formData.description" 
            placeholder="请输入品牌描述"
            :rows="4"
            :maxlength="500"
          />
        </lay-form-item>

        <lay-form-item label="官方网站" prop="website">
          <lay-input 
            v-model="formData.website" 
            placeholder="请输入官方网站地址"
            :maxlength="200"
          />
        </lay-form-item>





        <lay-form-item label="排序权重" prop="sortOrder" required>
          <lay-input-number 
            v-model="formData.sortOrder" 
            placeholder="数字越小越靠前"
            :min="0"
            :max="9999"
          />
        </lay-form-item>

        <lay-form-item label="显示状态" prop="isShow">
          <lay-switch 
            v-model="formData.isShow" 
            :value="1"
            :unvalue="0"
          />
          <span style="margin-left: 8px; color: #666;">
            {{ formData.isShow === 1 ? '显示' : '隐藏' }}
          </span>
        </lay-form-item>
      </lay-form>

      <div class="dialog-footer">
        <lay-button @click="handleClose">取消</lay-button>
        <lay-button type="primary" :loading="loading" @click="handleSubmit">
          {{ mode === 'add' ? '新增' : '保存' }}
        </lay-button>
      </div>
    </div>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { layer } from '@layui/layui-vue'
import { brandApi } from '../../../../api/module/brand'
import { UploadApi } from '../../../../api/module/upload'

interface Props {
  visible: boolean
  brandData?: any
  mode: 'add' | 'edit'
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  brandData: null,
  mode: 'add'
})

const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const formRef = ref()
const fileInput = ref()

// 表单数据
const formData = reactive({
  name: '',
  logo: '',
  description: '',
  website: '',
  sortOrder: 0,
  isShow: 1
})

// 监听visible变化
const visible = ref(props.visible)
watch(() => props.visible, (newVal) => {
  visible.value = newVal
  if (newVal) {
    initFormData()
  }
})

watch(visible, (newVal) => {
  emit('update:visible', newVal)
})

// 初始化表单数据
const initFormData = () => {
  if (props.mode === 'edit' && props.brandData) {
    Object.assign(formData, {
      name: props.brandData.name || '',
      logo: props.brandData.logo || '',
      description: props.brandData.description || '',
      website: props.brandData.website || '',
      sortOrder: props.brandData.sortOrder || 0,
      isShow: props.brandData.isShow ?? 1
    })
  } else {
    // 重置表单
    Object.assign(formData, {
      name: '',
      logo: '',
      description: '',
      website: '',
      sortOrder: 0,
      isShow: 1
    })
  }
}

// 处理关闭
const handleClose = () => {
  visible.value = false
}

// 处理提交
const handleSubmit = async () => {
  try {
    // 表单验证
    if (!formData.name.trim()) {
      layer.msg('请输入品牌名称', { icon: 3 })
      return
    }

    loading.value = true

    const submitData = {
      name: formData.name.trim(),
      logo: formData.logo || null,
      description: formData.description?.trim() || null,
      website: formData.website?.trim() || null,
      sortOrder: formData.sortOrder,
      isShow: formData.isShow
    }

    let response
    if (props.mode === 'add') {
      response = await brandApi.createBrand(submitData)
    } else {
      response = await brandApi.updateBrand(props.brandData.id, submitData)
    }

    if (response.code === 200) {
      layer.msg(props.mode === 'add' ? '新增成功' : '保存成功', { icon: 1 })
      emit('success')
      handleClose()
    }
  } catch (error) {
    layer.msg(props.mode === 'add' ? '新增失败' : '保存失败', { icon: 2 })
  } finally {
    loading.value = false
  }
}

// 处理Logo上传
const handleLogoUpload = () => {
  fileInput.value?.click()
}

// 处理Logo更换
const handleLogoChange = () => {
  fileInput.value?.click()
}

// 处理Logo删除
const handleLogoRemove = () => {
  formData.logo = ''
}

// 处理文件选择
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    layer.msg('请选择图片文件', { icon: 3 })
    return
  }

  // 验证文件大小（2MB）
  if (file.size > 2 * 1024 * 1024) {
    layer.msg('图片大小不能超过2MB', { icon: 3 })
    return
  }

  try {
    loading.value = true
    const response = await uploadApi.uploadImage(file)
    
    if (response.code === 200) {
      formData.logo = response.data.url
      layer.msg('Logo上传成功', { icon: 1 })
    }
  } catch (error) {
    layer.msg('Logo上传失败', { icon: 2 })
  } finally {
    loading.value = false
    // 清空文件输入
    target.value = ''
  }
}
</script>

<style scoped>
.brand-dialog {
  padding: 20px;
}

.logo-upload {
  width: 100%;
}

.logo-preview {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
}

.logo-preview img {
  width: 80px;
  height: 80px;
  object-fit: contain;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
}

.logo-actions {
  display: flex;
  gap: 8px;
}

.logo-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.logo-upload-area:hover {
  border-color: #1890ff;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}
</style>